package com.wsc.wisdomchina.ai;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;


import com.samton.floatWindow.FloatWindowService;
import com.samton.floatWindow.MyWindowManager;
import com.samton.interfaces.IBenFileCallBack;
import com.samton.interfaces.IBenHttpCallBack;
import com.samton.interfaces.IBenIMCallBack;
import com.samton.interfaces.IBenIMReceiveCallBack;
import com.samton.interfaces.IBenMsgCallBack;
import com.samton.interfaces.IBenRecordCallBack;
import com.samton.mainSDK.IBenChatSDK;
import com.samton.mainSDK.IBenRecordSDK;
import com.samton.model.AppGlobal;
import com.samton.model.Constants;
import com.samton.utils.DialogManager;
import com.samton.utils.MediaManager;
import com.samton.utils.ToastUtil;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;
import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.ai.adapter.AutoAdapter;
import com.wsc.wisdomchina.ai.adapter.GridViewAdapter;
import com.wsc.wisdomchina.ai.adapter.IBenDemoChatAdapter;
import com.wsc.wisdomchina.ai.db.DbManager;
import com.wsc.wisdomchina.ai.model.IBenDemoBean;
import com.wsc.wisdomchina.ai.utils.DbUtils;
import com.wsc.wisdomchina.ai.widget.MyDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


/**
 * 实例聊天界面
 */
public class IBenDemoChatActivity extends FragmentActivity implements OnClickListener, OnTouchListener, IBenRecordCallBack, IBenIMReceiveCallBack {
    public View popView;
    /**
     * 返回按钮
     */
    private RelativeLayout mTitleBack = null;
    /**
     * 聊天显示ListView
     */
    private ListView mListView = null;
    /**
     * 文字聊天层
     */
    private RelativeLayout mTextLayout = null;
    /**
     * 切换至语音按钮
     */
    private Button mChangeToVoice = null;
    /**
     * 文字输入框
     */
    private EditText mEditText = null;
    /**
     * 语音聊天层
     */
    private RelativeLayout mVoiceLayout = null;
    /**
     * 切换至文字按钮
     */
    private Button mChangeToText = null;
    /**
     * 按下说话按钮
     */
    private Button mRecordBtn = null;
    /**
     * 定时器
     */
    private Timer mTimer = null;
    /**
     * 刷新坐席状态的定时器
     */
    private Timer mRefreshTimer = null;
    /**
     * 坐席在线状态
     */
    private boolean isLogOut = true;
    /**
     * 录音时间
     */
    private float mRecordTime = 0;
    /**
     * 聊天适配器
     */
    private IBenDemoChatAdapter mListAdapter = null;
    /**
     * 聊天数据源
     */
    private List<IBenDemoBean> mMessageList = new ArrayList<>();
    /**
     * 录音显示对话框
     */
    private DialogManager mDialogManager;
    /**
     * 相似问题适配器
     */
    private AutoAdapter mSimilarAdapter = null;
    /**
     * 相似问题数据源
     */
    private List<String> mSimilarList = new ArrayList<>();
    /**
     * 图片数组们
     * <p>
     * /微笑/呲牙/憨笑/偷笑/鼓掌/敲打/晕/冷汗/惊讶
     * /撇嘴/酷/疑问/奋斗/流泪/可怜/害羞/擦汗/困/衰
     * /恐惧/发呆/大兵/猪头/流汗/抓狂/阴险/色/坏笑
     * /傲慢/白眼/鄙视/咒骂/发怒
     */
    private int[] e_pic = new int[]{
            R.mipmap.weixiao, R.mipmap.ciya, R.mipmap.hanxiao, R.mipmap.touxiao, R.mipmap.guzhang, R.mipmap.qiaoda,
            R.mipmap.yun, R.mipmap.lenghan, R.mipmap.jingya, R.mipmap.piezui, R.mipmap.ku, R.mipmap.yiwen, R.mipmap.fendou,
            R.mipmap.liulei, R.mipmap.kelian, R.mipmap.haixiu, R.mipmap.cahan, R.mipmap.kun, R.mipmap.shuai,
            R.mipmap.kongju, R.mipmap.fadai, R.mipmap.dabing, R.mipmap.zhutou, R.mipmap.liuhan, R.mipmap.zhuakuang,
            R.mipmap.yinxian, R.mipmap.se, R.mipmap.huaixiao, R.mipmap.aoman, R.mipmap.baiyan, R.mipmap.bishi,
            R.mipmap.zhouma, R.mipmap.fanu

    };

    private int[] more_pic = new int[]{R.mipmap.take_pic, R.mipmap.choose_pic, R.mipmap.icon_grade};
    /**
     * 当前与客服聊天的标记  TRUE 与客服连接  FALSE  与小笨聊天
     */
    private boolean CSflag = false;
    /**
     * 标记是表情图标还是 键盘
     */
    private boolean isEOrK = true;
    /**
     * 标记  是语音 还是键盘
     */
    private boolean isVOrK = true;
    /**
     * 等待 显示的弹窗
     */
    private Dialog myDialog = null;
    /**
     * 智能与客服切换按钮
     */
    private TextView intoCS;
    /**
     * 更多选项按钮
     */
    private Button mButton_more;
    /**
     * 点击更多或者表情时 选项布局
     */
    public RelativeLayout mChooseLay;
    /**
     * 显示表情图片  或显示更多选项
     */
    private GridView mGridView;
    /**
     * 界面最上方标题
     */
    private TextView mTextView_title;
    /**
     * 表情按钮
     */
    private Button mButton_biaoqing;
    /**
     * 表情图片  或显示更多选项适配器
     */
    private GridViewAdapter adapter = null;
    /**
     * 发送表情按钮
     */
    private Button mBtnSendEmoji;
    // 编辑框 输入文字时 编辑框上方显示的引导语布局
    private ListView mListView_yindao;
    private LinearLayout mLinnerlayout;
    private ImageView mImageView_guanbi;
    /**
     * 刷新UI的Handler
     */
    private Handler mHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                // 刷新UI
                case 0:
                    try {
                        JSONObject object = new JSONObject((String) msg.obj);
                        JSONObject data = object.getJSONObject("data");
                        // 成功返回
                        IBenDemoBean bean = new IBenDemoBean();
                        // 系统返回为0
                        bean.setType(MyConstant.TYPE_IBEN);
                        int answerType = data.optInt("answerType");
                        String message = data.optString("message");
                        String title = data.optString("title");
                        String imageUrl = data.optString("imageUrl");
                        String desc = data.optString("desc");
                        String htmlUrl = data.optString("htmlUrl");
                        // 返回类型0  纯文本1富文本
                        bean.setAnswerType(answerType);
                        // bean.setAnswerType(MyConstant.MESSAGE_TYPE_VOICE);
                        bean.setContent(message);
                        bean.setRichTitle(title);
                        bean.setRichImg(imageUrl);
                        bean.setRichDesc(desc);
                        bean.setFilePathString(htmlUrl);
                        // bean.setFilePathString(AppGlobal.getInstance().audioPath);
                        // 将信息 存入数据库
                        DbManager.insertIntoChatData(0, answerType, message, htmlUrl, null, null, title, imageUrl, desc);
                        mMessageList.add(bean);
                        // 刷新列表
                        mListAdapter.updateList(mMessageList);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                // 相似问题
                case 1:
                    if (mLinnerlayout.getVisibility() == View.GONE) {
                        mLinnerlayout.setVisibility(View.VISIBLE);
                    }
                    mSimilarAdapter.updateList(mSimilarList, (String) msg.obj);
                    break;
                // 更新音量
                case 2:
                    int volume = (int) msg.obj;
                    int voice = 0;
                    if (volume < 5) {
                        voice = 1;
                    }
                    if (5 <= volume && volume < 10) {
                        voice = 2;
                    }
                    if (10 <= volume && volume < 15) {
                        voice = 3;

                    }
                    if (15 <= volume && volume < 20) {
                        voice = 4;
                    }
                    if (20 <= volume && volume < 25) {
                        voice = 5;
                    }
                    if (25 <= volume && volume < 30) {
                        voice = 6;

                    }
                    if (30 <= volume) {
                        voice = 7;
                    }
                    mDialogManager.updateVoiceLevel(voice);
                    break;
                case 3:
                    //更新  客服发送的文本消息到 UI
                    IBenDemoBean bean = new IBenDemoBean();
                    bean.setContent((String) msg.obj);
                    bean.setAnswerType(MyConstant.MESSAGE_TYPE_TEXT);
                    bean.setType(MyConstant.TYPE_KEFU);
                    DbManager.insertIntoChatData(1, 0, (String) msg.obj, null, null, null, null, null, null);
                    mMessageList.add(bean);
                    // 刷新列表
                    mListAdapter.updateList(mMessageList);
                    break;
                case 4:
                    //更新 用户发送的图片到UI
                    IBenDemoBean benDemoBean = new IBenDemoBean();
                    benDemoBean.setContent((String) msg.obj);
                    benDemoBean.setAnswerType(MyConstant.MESSAGE_TYPE_IMAGE);
                    benDemoBean.setType(MyConstant.TYPE_USER);
                    DbManager.insertIntoChatData(2, 2, (String) msg.obj, null, null, null, null, null, null);
                    mMessageList.add(benDemoBean);
                    // 刷新列表
                    mListAdapter.updateList(mMessageList);
                    break;
                case 5:
                    //更新 用户发送的 文件  到UI
                    IBenDemoBean beanFile = new IBenDemoBean();
                    beanFile.setContent((String) msg.obj);
                    beanFile.setAnswerType(MyConstant.MESSAGE_TYPE_FILE);
                    beanFile.setType(MyConstant.TYPE_USER);
                    DbManager.insertIntoChatData(2, 4, (String) msg.obj, null, null, null, null, null, null);
                    mMessageList.add(beanFile);
                    // 刷新列表
                    mListAdapter.updateList(mMessageList);
                    break;
                case 6:
                    // 更新信息 到UI
                    mMessageList.add((IBenDemoBean) msg.obj);
                    mListAdapter.updateList(mMessageList);
                    break;
                case 7:
                    myDialog.dismiss();
                    ToastUtil.showToast("客服忙，请稍后再试");
                    mHandler.sendEmptyMessage(9);
                    break;
                case 8:
                    if (!CSflag) {
                        if (myDialog.isShowing()) {
                            myDialog.dismiss();
                        }
                        CSflag = true;
                        MyConstant.isIBen = false;
                        intoCS.setText(R.string.turniben);
                        mTextView_title.setText(R.string.titleCS);
                    }
                    break;
                case 9:
                    CSflag = false;
                    MyConstant.isIBen = true;
                    intoCS.setText(R.string.turncs);
                    mTextView_title.setText(R.string.titleMain);
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_ibendemo_chat);
        // 初始化控件
        initView();
        // 初始化数据
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 回退键 或返回时 访客与坐席 断开连接
        if (CSflag == true) {
            stopRefreshSeatState(false);
        }
    }

    /**
     * 停止刷新坐席状态
     *
     * @param isRefresh 坐席是否在线
     */
    private void stopRefreshSeatState(boolean isRefresh) {
        if (mRefreshTimer != null) {
            mRefreshTimer.cancel();
        }
        mHandler.sendEmptyMessage(9);
        if (isRefresh) {
            ToastUtil.showToast("客服已下线");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 移除悬浮窗并停止悬浮窗服务（没有启用悬浮窗的话请忽视）
        stopService(new Intent(getApplicationContext(), FloatWindowService.class));
        MyWindowManager.removeSmallWindow(this);
        //初始化聊天记录
        DbUtils.initChatData(mMessageList, mListAdapter);
        mListView.setSelection(mMessageList.size() - 1);
        // 获取推送通知点击时的结果 跳转与客服聊天界面
        XGPushClickedResult click = XGPushManager.onActivityStarted(this);
        if (click != null) {
            String content = click.getContent();
            //从通知中获取坐席的id
            String seatID = content.substring(content.lastIndexOf("【") + 1, content.lastIndexOf("】"));
            if (TextUtils.isEmpty(seatID)) {
                return;
            }
            if (CSflag) {
                //转换到和小笨聊天
                mHandler.sendEmptyMessage(9);
                return;
            } else {
                myDialog = MyDialog.getLoadDialog(IBenDemoChatActivity.this, getResources().getText(R.string.turning).toString());
                myDialog.show();

            }
            //切换至文字聊天
            mTextLayout.setVisibility(View.VISIBLE);
            mVoiceLayout.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null || isLogOut) {
            // 客服下线后不让发图片
            ToastUtil.showToast("客服已下线~");
            return;
        }
        Uri uri = null;
        uri = data.getData();
        // 选择照片上传
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            final Uri finalUri1 = uri;
        }
        // 拍照上传
        else if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
            String sdStatus = Environment.getExternalStorageState();
            if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
                return;
            }
            if (data == null) {
                return;
            }
            new DateFormat();
            //根据时间设置图片名称
            String name = DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA)) + ".jpg";
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            FileOutputStream b = null;
            //创建文件夹
            File file = new File(MyConstant.PATH);
            if (!file.exists()) {
                file.mkdirs();// 创建文件夹
            }
            //设置图片名称
            String fileName = MyConstant.PATH + "/" + name;
            //把图片写入sdCard
            try {
                b = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //获取图片绝对路径
            String mFilePathUri = file.getAbsolutePath() + "/" + name;
            //获取图片  URI
            uri = Uri.fromFile(new File(mFilePathUri));
            final Uri finalUri1 = uri;

        } else if (requestCode == 300 && resultCode == Activity.RESULT_OK) {
//            manager.upLoadText(uri, new IHttpCallBack() {
//                @Override
//                public void onSuccess(String result) {
//                    manager.upLoadSuccess(result);
//                    try {
//                        JSONObject object = new JSONObject(result);
//                        int rs = object.optInt("rs");
//                        if (rs == 1) {
//                            object = object.getJSONObject("data");
//                            String attachmentName = object.optString("attachmentName");
//                            Message message = mHandler.obtainMessage(5, attachmentName);
//                            mHandler.sendMessage(message);
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//
//                @Override
//                public void onFailed(String message) {
//
//                }
//            });
        }
    }

    /**
     * 初始化控件
     */
    private void initView() {
        popView = findViewById(R.id.mTitleLayout);
        mTitleBack = (RelativeLayout) findViewById(R.id.iben_chat_back);
        mListView = (ListView) findViewById(R.id.mListView);
        mTextLayout = (RelativeLayout) findViewById(R.id.mTextLayout);
        mChangeToVoice = (Button) findViewById(R.id.mChangeToVoice);
        mEditText = (EditText) findViewById(R.id.mEditText);
        mVoiceLayout = (RelativeLayout) findViewById(R.id.mVoiceLayout);
        mChangeToText = (Button) findViewById(R.id.mChangeToText);
        mRecordBtn = (Button) findViewById(R.id.mRecordBtn);
        mButton_biaoqing = ((Button) findViewById(R.id.mButton_biaoqing));
        //常用语引导部分
        mLinnerlayout = ((LinearLayout) findViewById(R.id.mLinearlayout_yindao));
        mListView_yindao = ((ListView) findViewById(R.id.mListView_yindao));
        mImageView_guanbi = ((ImageView) findViewById(R.id.mImageView_cancal));
        //转人工
        mTextView_title = (TextView) findViewById(R.id.mTextView_title);
        mButton_more = (Button) findViewById(R.id.mButton_more);
        mChooseLay = (RelativeLayout) findViewById(R.id.mChooseLay);
        mGridView = (GridView) findViewById(R.id.mGridView);
        mBtnSendEmoji = ((Button) findViewById(R.id.mBtnSendEmoji));


        intoCS = (TextView) findViewById(R.id.intoCS);
        mImageView_guanbi.setOnClickListener(this);
        mButton_more.setOnClickListener(this);
        intoCS.setOnClickListener(this);
        mBtnSendEmoji.setOnClickListener(this);
        // ***************监听******************/
        mButton_biaoqing.setOnClickListener(this);
        mTitleBack.setOnClickListener(this);
        mChangeToVoice.setOnClickListener(this);
        mChangeToText.setOnClickListener(this);
        mRecordBtn.setOnTouchListener(this);
        mListView.setSelection(mMessageList.size() - 1);
        mListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 点击到之后隐藏输入法、隐藏选择照片层
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    hideKeyBoard();
                    mChooseLay.setVisibility(View.GONE);
                } else {
                    v.performClick();
                }
                return false;
            }

        });
        mEditText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 判断如果是输入法的回车按键或者是发送按钮的话发送消息
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    // 发送消息
                    final String sendMsg = mEditText.getText().toString().trim();
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            if (!TextUtils.isEmpty(sendMsg)) {
                                // 判断 在与谁聊天
                                if (!CSflag) {
                                    sendMessage(sendMsg, 0);
                                    receiveMessage(sendMsg);
                                } else {
                                    //清空编辑框
                                    mEditText.setText("");
                                    // 调用sdk方法向人工客服发送文字消息
                                    sendCSMessage(sendMsg, MyConstant.MESSAGE_TYPE_TEXT);
                                }
                            }
                            break;
                    }
                    //发送完毕  让引导语  布局消失
                    if (mLinnerlayout.getVisibility() == View.VISIBLE) {
                        mLinnerlayout.setVisibility(View.GONE);
                    }
                    return true;
                } else {
                    return false;
                }
            }
        });
        // 相似问题查询点击效果
        mListView_yindao.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView mTextView = (TextView) view;
                String text = mTextView.getText().toString().trim();
                String substring = text.substring(text.indexOf(".") + 1, text.length());
                mEditText.setText(substring);
            }
        });
        //点击编辑框
        mEditText.setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        // 录音SDK
        IBenRecordSDK.getInstance().init(this);
        IBenRecordSDK.getInstance().setCallBack(this);
        // 初始化框体
        mDialogManager = new DialogManager(this);
        // 初始化聊天列表
        mListAdapter = new IBenDemoChatAdapter(this, mMessageList);
        mListView.setAdapter(mListAdapter);
        // 自动填充的适配器
        mSimilarAdapter = new AutoAdapter(this, mSimilarList);
        // 添加适配器
        mListView_yindao.setAdapter(mSimilarAdapter);
//        mEditText.setAdapter(mSimilarAdapter);
        mEditText.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        if (mChooseLay.getVisibility() == View.VISIBLE) {
                            mChooseLay.setVisibility(View.GONE);
                        }
                        break;
                }
                return false;
            }
        });
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // s--改变之后的新内容
                // start--内容被改变的开始位置
                // before--原始文字被删除的个数
                // count--新添加的内容的个数
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // s--未改变之前的内容
                // start--内容被改变的开始位置
                // count--原始文字被删除的个数
                // after--新添加的内容的个数
            }

            @Override
            public void afterTextChanged(Editable s) {
                // s--最终内容
                if (!CSflag) {
                    querySimilar(s.toString().trim());
                }

            }
        });

    }
    //messageType  0：纯文本，1：富文本，2：图片，3：语音， 4：文件
    //  SendType  0:系统回复，1：客服回复，2：客户消息

    /**
     * 更新 发送给小笨的消息  到界面
     *
     * @param message     要发送的信息
     * @param messageType 0:文字3:语音
     */
    private void sendMessage(String message, int messageType) {
        IBenDemoBean bean = new IBenDemoBean();
        bean.setType(MyConstant.TYPE_USER);
        if (messageType == 0) {
            bean.setAnswerType(messageType);
            bean.setContent(message);
            DbManager.insertIntoChatData(2, 0, message, null, null, null, null, null, null);
        } else if (messageType == 3) {
            float time = MediaManager.getTime(AppGlobal.getInstance().audioPath);
            bean.setAnswerType(messageType);
            // 语音文件地址
            bean.setFilePathString(AppGlobal.getInstance().audioPath);
            // 语音时间
            bean.setTime(time);
            DbManager.insertIntoChatData(2, 3, message, AppGlobal.getInstance().audioPath, time, null, null, null, null);
        }
        mMessageList.add(bean);
        // 刷新列表
        mListAdapter.updateList(mMessageList);
    }

    //更新 发送 给客服 的消息到 界面
    private void sendCSMessage(String message, int messageType) {
        IBenDemoBean bean = new IBenDemoBean();
        bean.setType(MyConstant.TYPE_USER);
        if (messageType == MyConstant.MESSAGE_TYPE_TEXT) {
            bean.setAnswerType(messageType);
            bean.setContent(message);
            DbManager.insertIntoChatData(2, 0, message, null, null, null, null, null, null);

        } else if (messageType == MyConstant.MESSAGE_TYPE_VOICE) {
            float time = MediaManager.getTime(AppGlobal.getInstance().audioPath);
            bean.setAnswerType(messageType);
            // 语音文件地址
            bean.setFilePathString(AppGlobal.getInstance().audioPath);
            // 语音时间
            bean.setTime(time);
            DbManager.insertIntoChatData(2, 0, null, AppGlobal.getInstance().audioPath, time, null, null, null, null);
        }
        Message msg = mHandler.obtainMessage(6, bean);
        mHandler.sendMessage(msg);
    }

    /**
     * 根据发送的消息接受小笨的返回信息
     *
     * @param message 要发送的信息
     */
    private void receiveMessage(final String message) {
        // 清空编辑框
        mEditText.setText("");
        IBenChatSDK.send2IBen(message, new IBenMsgCallBack() {
            @Override
            public void onSuccess(boolean isAnswer, String s) {
                Log.e("Liu", "onSuccess: 发送成功 " + s);
                if (isAnswer) {
                    String ss = s.replace("\\n", "<br>");
                    Message msg = mHandler.obtainMessage(0, ss);
                    mHandler.sendMessage(msg);
                } else {
                    IBenDemoBean iBenDemoBean = new IBenDemoBean();
                    iBenDemoBean.setAnswerType(0);
                    // iBenDemoBean.setAnswerType(MyConstant.MESSAGE_TYPE_VOICE);
                    iBenDemoBean.setType(MyConstant.TYPE_IBEN);
                    StringBuilder builder = new StringBuilder();
                    try {
                        JSONObject object = new JSONObject(s);
                        String prefix = (String) object.opt("prefix");
                        builder.append(prefix);
                        JSONArray message1 = object.getJSONArray("message");
                        if (message1 != null && message1.length() > 0) {
                            for (int i = 0; i < message1.length(); i++) {
                                JSONObject jsonObject = message1.getJSONObject(i);
                                String message2 = (String) jsonObject.opt("message");
                                builder.append("<br>" + (i + 1) + "." + message2);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    iBenDemoBean.setContent(builder.toString());
                    DbManager.insertIntoChatData(0, 0, builder.toString(), null, null, null, null, null, null);
                    Message msg = mHandler.obtainMessage(6, iBenDemoBean);
                    mHandler.sendMessage(msg);
                }
            }

            @Override
            public void onFailed(String s) {

            }
        });
    }

    /**
     * 查询相似问题
     *
     * @param sendMsg 要查询的问题
     */
    private void querySimilar(final String sendMsg) {
        IBenChatSDK.querySimilar(sendMsg, new IBenHttpCallBack() {

            @Override
            public void onSuccess(String message) {
                if (!TextUtils.isEmpty(message)) {
                    try {
                        JSONArray jsonArray = new JSONArray(message);
                        // 清空相似问题列表
                        mSimilarList.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            // 向列表中添加相似问题
                            mSimilarList.add(jsonObject.optString("originQuestion"));
                        }
                        Message msg = mHandler.obtainMessage(1, sendMsg);
                        mHandler.sendMessage(msg);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailed(String s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iben_chat_back: // 返回按钮
                goBack();
                break;
            case R.id.mChangeToVoice: // 切换至语音聊天
                //标记此时为 语音聊天
                isVOrK = true;
                //语音聊天时  切换到表情
                isEOrK = true;
                //改变图标
                changeIcon();
                mTextLayout.setVisibility(View.GONE);
                mVoiceLayout.setVisibility(View.VISIBLE);
                // 语音聊天时  底部按钮置底
                if (mChooseLay.getVisibility() == View.VISIBLE) {
                    mChooseLay.setVisibility(View.GONE);
                }
                hideKeyBoard();
                break;
            case R.id.mChangeToText: // 切换至文字聊天
                //标记此时是文字聊天
                isVOrK = false;
                //文字聊天时  切换到表情
                isEOrK = true;
                //改变图标
                changeIcon();
                mTextLayout.setVisibility(View.VISIBLE);
                mVoiceLayout.setVisibility(View.GONE);
                break;
            case R.id.intoCS://切换与客服聊天
                //判断当前 是与谁连接CSflag为true 时
                if (CSflag) {
                    //转换到和小笨聊天
                    mHandler.sendEmptyMessage(9);
                    return;
                } else {
                    myDialog = MyDialog.getLoadDialog(IBenDemoChatActivity.this, getResources().getText(R.string.turning).toString());
                    myDialog.show();
                }
                // 切换至文字聊天
                mTextLayout.setVisibility(View.VISIBLE);
                mVoiceLayout.setVisibility(View.GONE);
                break;
            case R.id.mButton_more: //点击 更多按钮
                changeLayout(2);
                break;
            case R.id.mButton_biaoqing://点击表情按钮
                changeLayout(1);
                break;
            case R.id.mEditText: //如果图片选择 区域显示   让它消失
                if (mChooseLay.getVisibility() == View.VISIBLE) {
                    mChooseLay.setVisibility(View.GONE);
                }
                break;
            // 发送表情
            case R.id.mBtnSendEmoji:
                String sendMsg = mEditText.getText().toString().trim();
                if (!TextUtils.isEmpty(sendMsg)) {
                    // 判断在与谁聊天 TODO问题之一
                    if (!CSflag) {
                        sendMessage(sendMsg, 0);
                        receiveMessage(sendMsg);
                    } else {
                        //清空编辑框
                        mEditText.setText("");
                        //更新 ui
                        sendCSMessage(sendMsg, MyConstant.MESSAGE_TYPE_TEXT);
                        // 调用 sdk 方法向人工 客服 发送文字消息
                        // manager.setMessage(sendMsg);
                    }
                }
                break;
            case R.id.mImageView_cancal:
                if (mLinnerlayout.getVisibility() == View.VISIBLE) {
                    mLinnerlayout.setVisibility(View.GONE);
                }
                break;
        }
    }

    //显示或隐藏 输入法  隐藏时 显示 ，显示时隐藏
    private void controlKeyBord() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //隐藏输入法
    private void hideKeyBoard() {
        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).
                hideSoftInputFromWindow(mEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    //软键盘与表情 图标转换
    private void changeIcon() {
        if (isEOrK) {
            mButton_biaoqing.setBackgroundResource(R.mipmap.chat_expression);
        } else {
            mButton_biaoqing.setBackgroundResource(R.mipmap.chat_keyboard);
        }
    }

    /**
     * 切换 布局
     *
     * @param type 点击按钮的类型  1 点击的表情或软键盘 （右边的）
     *             2 点击的更多按钮
     */
    private void changeLayout(int type) {
        if (mChooseLay.getVisibility() == View.GONE) {
            mChooseLay.setVisibility(View.VISIBLE);
        }
        if (type == 1) {
            if (isEOrK) {
                hideKeyBoard();
                isEOrK = false;
            } else {
                //如果此时是语音聊天  转变为文字聊天
                if (isVOrK) {

                    isVOrK = false;
                    //文字聊天时  切换到表情
                    isEOrK = true;
                    //改变图标
                    changeIcon();
                    mTextLayout.setVisibility(View.VISIBLE);
                    mVoiceLayout.setVisibility(View.GONE);
                }

                controlKeyBord();
                mChooseLay.setVisibility(View.GONE);
                isEOrK = true;
            }
            isVOrK = false;
            mTextLayout.setVisibility(View.VISIBLE);
            mVoiceLayout.setVisibility(View.GONE);
            changeIcon();
        } else {
            hideKeyBoard();
        }
        // 根据点击的按钮不同  显示不同的内容
        if (type == 1) {
            if (mBtnSendEmoji.getVisibility() == View.GONE) {
                mBtnSendEmoji.setVisibility(View.VISIBLE);
            }
            mGridView.setNumColumns(8);
            adapter = new GridViewAdapter(this, e_pic, 1);
            mGridView.setAdapter(adapter);
        } else {
            if (mBtnSendEmoji.getVisibility() == View.VISIBLE) {
                mBtnSendEmoji.setVisibility(View.GONE);
            }
            mGridView.setNumColumns(4);
            adapter = new GridViewAdapter(this, more_pic, 2);
            mGridView.setAdapter(adapter);
        }
        Point size = new Point();
        final WindowManager managers = this.getWindowManager();
        managers.getDefaultDisplay().getSize(size);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, size.y / 3);
        mChooseLay.setLayoutParams(mLayoutParams);
    }

    /**
     * 返回方法 返回并启动小笨服务(如果语音正在播放的话停止语音播放)
     */
    private void goBack() {
        // 停止播放
        MediaManager.release();
        // 停止刷新坐席状态
        stopRefreshSeatState(false);
        // 结束当前的Activity
        finish();
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            // 手指按下
            case MotionEvent.ACTION_DOWN:
                // 清空录音时间
                mRecordTime = 0;
                // 布局显示录音动画
                mRecordBtn.setBackgroundResource(R.drawable.button_recording);
                mRecordBtn.setText(R.string.recording);
                mDialogManager.showRecordingDialog();
                // 开始录音
                IBenRecordSDK.getInstance().startRecord();
                // 定时器设置
                if (mTimer != null) {
                    mTimer = null;
                }
                mTimer = new Timer();
                mTimer.schedule(new RequestTimerTask(), 0, 100);
                break;
            // 手指移动
            case MotionEvent.ACTION_MOVE:
                break;
            // 手指抬起
            case MotionEvent.ACTION_UP:
                // 布局显示录音动画
                mRecordBtn.setBackgroundResource(R.drawable.button_recordnormal);
                mRecordBtn.setText(R.string.normal);
                // 停止录音
                IBenRecordSDK.getInstance().stopRecord();
                mDialogManager.dismissDialog();
                mTimer.cancel();
                // 录音时间小于1秒
                if (mRecordTime < 1) {
                    ToastUtil.showToast("录音时间过短！");
                }
                break;
            default:
                view.performClick();
                break;
        }
        return false;
    }

    //**********************************sdk  提供的  接口回调 ******************************

    /**
     * 定时任务
     *
     * @author syk
     */
    class RequestTimerTask extends TimerTask {
        public void run() {
            mRecordTime += 0.1;
        }
    }

    class RefreshSeatTimer extends TimerTask {
        @Override
        public void run() {

        }
    }

    /**
     * 开始录音
     */
    @Override
    public void onBeginOfSpeech() {

    }

    /**
     * 声音大小变更
     */
    @Override
    public void onVolumeChanged(int i, byte[] bytes) {
        Message msg = mHandler.obtainMessage(2, i);
        mHandler.sendMessage(msg);
    }

    /**
     * 结束录音
     */
    @Override
    public void onEndOfSpeech() {
        mDialogManager.dismissDialog();
    }

    /**
     * 语音听写结果 回调
     */
    @Override
    public void onResult(String result) {
        if (mRecordTime < 1) {
            return;
        }
        if (!CSflag) {
            // 发送听写结果到小笨服务器
            sendMessage(result, 3);
            //调用接收消息方法
            receiveMessage(result);
        } else {
            IBenDemoBean bean = new IBenDemoBean();
            float time = MediaManager.getTime(AppGlobal.getInstance().audioPath);
            bean.setType(2);
            bean.setAnswerType(3);
            // 语音文件地址
            bean.setFilePathString(AppGlobal.getInstance().audioPath);
            // 语音时间
            bean.setTime(time);
            DbManager.insertIntoChatData(2, 3, null, AppGlobal.getInstance().audioPath, time, null, null, null, null);
            mMessageList.add(bean);
            // 刷新列表
            mListAdapter.updateList(mMessageList);

        }

    }

    @Override
    public void onGetFileMsg(int type, String fileName, String fileUrl, String msgID) {
        final IBenDemoBean bean = new IBenDemoBean();
        bean.setType(MyConstant.TYPE_KEFU);
        switch (type) {
            // 文件
            case Constants.MESSAGE_TYPE_FILE:
                bean.setAnswerType(MyConstant.MESSAGE_TYPE_FILE);
                bean.setContent(fileName);
                bean.setFilePathString(fileUrl);
                DbManager.insertIntoChatData(1, 4, fileName, fileUrl, null, null, null, null, null);
                Message message2 = mHandler.obtainMessage(6, bean);
                mHandler.sendMessage(message2);

                break;
            // 图片
            case Constants.MESSAGE_TYPE_IMG:
                bean.setAnswerType(MyConstant.MESSAGE_TYPE_IMAGE);
                bean.setFilePathString(fileUrl);
                DbManager.insertIntoChatData(1, 2, null, fileUrl, null, null, null, null, null);
                Message message = mHandler.obtainMessage(6, bean);
                mHandler.sendMessage(message);

                break;
            // 声音
            case Constants.MESSAGE_TYPE_VOICE:
                IBenChatSDK.downLoadFile(fileUrl, fileName, new IBenFileCallBack() {
                    @Override
                    public void onSuccess(File file) {
                        float time = MediaManager.getTime(file.getAbsolutePath());
                        bean.setTime(time);
                        bean.setType(MyConstant.TYPE_KEFU);
                        bean.setAnswerType(MyConstant.MESSAGE_TYPE_VOICE);
                        bean.setFilePathString(file.getAbsolutePath());
                        DbManager.insertIntoChatData(1, 3, null, file.getAbsolutePath(), time, "0", null, null, null);
                        Message message = mHandler.obtainMessage(6, bean);
                        mHandler.sendMessage(message);
                    }

                    @Override
                    public void onFailed(String s) {

                    }
                });
                break;

        }
    }

    @Override
    public void onGetStringMsg(String s, String msgID) {
        Message data = mHandler.obtainMessage(3, s);
        mHandler.sendMessage(data);

    }
}
